//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import { GitExtraInfo, NodeData } from '../types';
import { observer } from 'mobx-react';
import LocalNodeWrap from '../LocalNodeWrap';
import type { AtomGitIssue } from "@/api/atomgit/issue";
import { list_issue } from "@/api/atomgit/issue";
import { Button, Space, Table } from 'antd';
import { ExportOutlined, ReloadOutlined } from '@ant-design/icons';
import type { AtomGitRepo } from "@/api/atomgit/repo";
import { get_repo } from "@/api/atomgit/repo";
import { get_type_name, get_source, type UserDataSourceInfo, type GitSourceInfo } from '@/api/user_dataview';
import { open as shell_open } from '@tauri-apps/api/shell';
import UserPhoto from '@/components/Portrait/UserPhoto';
import type { ColumnsType } from 'antd/lib/table';
import moment from 'moment';


const AtomGitIssueListNode = (props: NodeProps<NodeData>) => {
    const [issueList, setIssueList] = useState<AtomGitIssue[]>([]);
    const [repoInfo, setRepoInfo] = useState<AtomGitRepo | null>(null);

    const [dataSource, setDataSource] = useState<UserDataSourceInfo | undefined>(undefined);

    const loadDataSource = async () => {
        const res = await get_source(props.data.dataSourceId ?? "");
        setDataSource(res);
    };

    const loadRepoInfo = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const extraInfo = props.data.extraInfo as GitExtraInfo;
        const res = await get_repo(sourceInfo.accessToken, extraInfo.ownerName, extraInfo.repoName);
        setRepoInfo(res);
    };

    const loadIssueList = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const extraInfo = props.data.extraInfo as GitExtraInfo;
        const res = await list_issue(sourceInfo.accessToken, extraInfo.ownerName, extraInfo.repoName, {
            sort: "created",
            direction: "desc",
            page: 1,
            per_page: 30,
        });
        setIssueList(res);
    };

    const getSourceTypeName = () => {
        if (dataSource == undefined) {
            return "";
        }
        return get_type_name(dataSource.source_type);
    };

    const columns: ColumnsType<AtomGitIssue> = [
        {
            title: "标题",
            width: 200,
            render: (_, row: AtomGitIssue) => (
                <a href={row.html_url} target="_blank" rel="noreferrer">{row.title}&nbsp;<ExportOutlined /></a>
            ),
        },
        {
            title: "锁定",
            width: 80,
            render: (_, row: AtomGitIssue) => row.locked ? "是" : "否",
        },
        {
            title: "提交人",
            width: 150,
            render: (_, row: AtomGitIssue) => (
                <a href={row.user.html_url} target="_blank" rel="noreferrer">
                    <Space>
                        <UserPhoto logoUri={row.user.avatar_url} style={{ width: "16px", borderRadius: "10px" }} />
                        <div>{row.user.login}&nbsp;<ExportOutlined /></div>
                    </Space>
                </a>
            ),
        },
        {
            title: "指派人",
            width: 100,
            render: (_, row: AtomGitIssue) => (
                <>
                    {row.assignee != undefined && row.assignee.id != undefined && (
                        <a href={row.assignee.html_url} target="_blank" rel="noreferrer">
                            <Space>
                                <UserPhoto logoUri={row.assignee.avatar_url} style={{ width: "16px", borderRadius: "10px" }} />
                                <div>{row.assignee.login}&nbsp;<ExportOutlined /></div>
                            </Space>
                        </a>
                    )}
                </>
            ),
        },
        {
            title: "创建时间",
            width: 120,
            render: (_, row: AtomGitIssue) => moment(row.created_at).format("YYYY-MM-DD HH:mm"),
        },
        {
            title: "更新时间",
            width: 120,
            render: (_, row: AtomGitIssue) => moment(row.updated_at).format("YYYY-MM-DD HH:mm"),
        },
        {
            title: "关闭时间",
            width: 120,
            render: (_, row: AtomGitIssue) => (
                <>
                    {row.closed_at != undefined && row.closed_at != "" && moment(row.closed_at).format("YYYY-MM-DD HH:mm")}
                </>
            ),
        },
    ];

    useEffect(() => {
        loadDataSource();
    }, []);

    useEffect(() => {
        if (dataSource != undefined) {
            loadRepoInfo();
            loadIssueList();
        }
    }, [dataSource]);

    return (
        <LocalNodeWrap title={
            <Space>
                <span>{getSourceTypeName()}</span>
                <span>工单列表</span>
                {repoInfo != null && (
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open(repoInfo.html_url);
                    }}>{repoInfo.full_name}</a>
                )}
            </Space>
        } nodeData={props} extraButtonList={[
            <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                loadIssueList();
            }} title='刷新' />
        ]} canChangeBgColor={false}>
            <Table rowKey="id" dataSource={issueList} columns={columns} pagination={false} scroll={{ y: props.data.height - 100 }} className="nodrag nopan nowheel"
                style={{ backgroundColor: props.data.bgColor ?? "white" }} />
        </LocalNodeWrap>
    );
};

export default observer(AtomGitIssueListNode);